package com.talent.service.impl;

import com.talent.handler.BaseException;
import com.talent.mapper.CategoryMapper;
import com.talent.pojo.dto.CategoryDTO;
import com.talent.pojo.entity.Category;
import com.talent.service.CategoryService;
import com.talent.service.OperationLogService;
import com.talent.utils.OperationLogUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private OperationLogService operationLogService;

    /**
     * 根据类型查询分类列表
     */
    @Override
    public List<Category> getByType(String type) {
        return categoryMapper.getWithSpotCount(type);
    }

    /**
     * 根据ID查询分类
     */
    @Override
    public Category getById(Long id) {
        return categoryMapper.getById(id);
    }

    /**
     * 新增分类
     */
    @Override
    public void save(CategoryDTO categoryDTO) {
        Category sqlCategory = categoryMapper.getByName(categoryDTO.getName());
        if (sqlCategory != null) {
            throw new BaseException("分类名称已存在");
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.insert(category);
        // 记录详细操作日志
        operationLogService.saveDetail(OperationLogUtils.buildCreateLog(
                "category", category.getId(), category.getName(), category));
    }

    /**
     * 更新分类
     */
    @Override
    public void update(Long id, CategoryDTO categoryDTO) {
        Category category = categoryMapper.getById(id);
        if (category == null) {
            throw new BaseException("分类不存在");
        }

        // 保存更新前的数据
        Category oldCategory = new Category();
        BeanUtils.copyProperties(category, oldCategory);

        BeanUtils.copyProperties(categoryDTO, category);
        category.setId(id);
        categoryMapper.update(category);

        // 记录详细操作日志
        operationLogService.saveDetail(OperationLogUtils.buildUpdateLog(
                "category", id, category.getName(), oldCategory, category));
    }

    /**
     * 删除分类
     */
    @Override
    public void deleteById(Long id) {
        Category category = categoryMapper.getById(id);
        if (category == null) {
            throw new BaseException("分类不存在");
        }

        categoryMapper.deleteById(id);

        // 记录详细操作日志
        operationLogService.saveDetail(OperationLogUtils.buildDeleteLog(
                "category", id, category.getName(), category));
    }
}
